package com.example.replacebooks.service;

import cn.hutool.core.date.DateUtil;
import com.example.replacebooks.common.JwtTokenUtils;
import com.example.replacebooks.entity.Class;
import com.example.replacebooks.entity.Notice;
import com.example.replacebooks.entity.Params;
import com.example.replacebooks.entity.User;
import com.example.replacebooks.exception.CustomException;
import com.example.replacebooks.mapper.ClassMapper;
import com.example.replacebooks.mapper.NoticeMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class NoticeService {
    @Resource
    private NoticeMapper noticeMapper;

    public List<Notice> findAll(){
        return noticeMapper.selectall();
    }

    public PageInfo<Notice> findBySearch(Params params){
        User currentUser = JwtTokenUtils.getCurrentUser();
        Integer role = currentUser.getRole();
        // 开启分页查询
        PageHelper.startPage(params.getPageNum(),params.getPageSize());
        // 接下来的查询会自动按照当前开启的分页查询
        List<Notice> list = noticeMapper.findBySearch(params,role);
        return PageInfo.of(list);
    }

    public void add(Notice notice) {
        // 进行重复性判断，同一id的分类替换，不同id新增
        Notice noticeid = noticeMapper.findByNoticeid(notice.getNoticeid());
        if (noticeid != null){
            // 该id已存在
            noticeMapper.updateByNoticeidid(notice);
        }else{
            User currentUser = JwtTokenUtils.getCurrentUser();
            Integer userid = currentUser.getUserid();
            notice.setUserid(userid);
            notice.setTime(DateUtil.now());
            noticeMapper.insertSelective(notice);
        }
    }

    public void delete(Integer noticeid) {
        noticeMapper.deleteByPrimaryKey(noticeid);
    }

}
